package io.hellsinger.viewmodel

abstract class BitViewModel<UiState>(
    scopeName: String,
    private var event: Int = IDLE,
) : BaseViewModel(scopeName) {
    protected var onEvent: UiStateUpdateCollector<UiState>? = null

    open fun collectUiState(collector: UiStateUpdateCollector<UiState>) {
        onEvent = collector
    }

    fun cancelCollectUiState() {
        onEvent = null
    }

    abstract fun getUiState(): UiState

    protected suspend fun update(event: Int) {
        onEvent?.emit(event, getUiState())
    }

    override fun onDestroy() {
        cancelCollectUiState()
        super.onDestroy()
    }

    fun interface UiStateUpdateCollector<UiState> {
        suspend fun emit(
            event: Int,
            state: UiState,
        )
    }

    companion object {
        const val IDLE = -1
    }
}
